package com.yans.managers
{
	import com.yans.interfaces.ITimeManager;
	
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	public class TimeManager implements ITimeManager
	{  
		
		private var timerDic:Dictionary;
		private var funcToTimerDic:Dictionary;	//key:fun 	存放计时器
		private var funcListDic:Dictionary;		//key:delay 存放函数
		
		public function TimeManager() { 
			timerDic = new Dictionary();
			funcToTimerDic = new Dictionary();
			funcListDic = new Dictionary();
		} 
		
		public function add(delay:int,func:Function):void
		{
			if(funcToTimerDic[func]) 
				return;
			funcToTimerDic[func] = createTimer(delay);
			funcListDic[delay].push(func);
		}
		
		public function remove(func:Function):void
		{
			if(!funcToTimerDic[func])
				return;
			var timer:Timer = funcToTimerDic[func];
			delete funcToTimerDic[func];
			
			var list:Array = funcListDic[timer.delay];
			if(list.indexOf(func)>-1) {
				list.splice(list.indexOf(func),1);
			}
			
			if(list.length==0) {
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER,timerHandler);
				delete funcListDic[timer.delay];
				delete timerDic[timer.delay];
			}
		}
		
		private function createTimer(delay:int):Timer {
			if(!timerDic.hasOwnProperty(delay)){
				var timer:Timer = new Timer(delay);
				timer.addEventListener(TimerEvent.TIMER,timerHandler);
				timer.start();
				timerDic[delay]= timer;
			}
			if(!funcListDic.hasOwnProperty(delay)){
				funcListDic[delay] = new Array();
			}
			return timerDic[delay];
		}
		
		private function timerHandler(e:TimerEvent):void
		{
			var list:Array = funcListDic[Timer(e.target).delay];
			for(var i:* in list) {
				list[i]();
			}
		}
		
	}
}